#include <odbc/statement.hpp>
#include <odbc/connection.hpp>
#include <odbc/odbc_error.hpp>
#include <sql.h>
#include <boost/foreach.hpp>

namespace odbc
{

statement::statement( const connection& conn, const std::string& statementString)
	: handle_( SQL_NULL_HANDLE), statementString_( statementString)
{
	odbc_error::check_success( 
		SQLAllocHandle( SQL_HANDLE_STMT, conn.handle_, &handle_),
		conn);

	this->prepare_statement();
}

// ---------------------------------------------------------------------------------------------------------------------

statement::~statement()
{
	BOOST_FOREACH( parameter* p_param, parameters_)
	{
		delete p_param;
	}
	SQLFreeStmt( handle_, SQL_CLOSE);
	SQLFreeHandle( SQL_HANDLE_STMT, handle_);
}

// ---------------------------------------------------------------------------------------------------------------------

void statement::prepare_statement()
{
	SQLRETURN retCode = SQLPrepare(
		handle_,
		(SQLCHAR*)statementString_.c_str(),
		SQLINTEGER( statementString_.size()));
	odbc_error::check_success( retCode, *this);
}

// ---------------------------------------------------------------------------------------------------------------------

void statement::execute()
{
	this->close_cursor();
	this->execute_statement();
}

// ---------------------------------------------------------------------------------------------------------------------

void statement::execute_statement()
{
	SQLRETURN retCode = SQLExecute( handle_);
	odbc_error::check_success( retCode, *this);
}

// ---------------------------------------------------------------------------------------------------------------------

void statement::close_cursor()
{
	SQLCloseCursor( handle_);
}

} // namespace odbc